package com.entrogy.controller;

import com.entrogy.bean.*;
import com.entrogy.config.Result;
import com.entrogy.service.*;
import com.entrogy.utils.constants.ErrorEnum;
import com.github.pagehelper.PageHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;


import java.util.*;

/**  群主管理控制层接口
 * @Author 许红松
 * @date 2019/5/30 0030 上午 11:54
 */
@RestController
@Transactional
@RequestMapping(value = "/group")
@Api(description = "对群主管理信息操作的相关接口")
public class GroupController {

    @Autowired
    private GroupService  groupService;//
    @Autowired
    private UserService userService;//
    @Autowired
    private MessageService messageService;//
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private ClassService classService;//

    @Autowired
    private ParentService parentService;

    @ApiOperation(value = "分页获取所有群主流水")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "分组名", name = "groupName", dataType = "String", paramType = "query"),
            @ApiImplicitParam(value = "教师群组或家长群组", name = "istoTeacher", dataType = "String", paramType = "query"),
            @ApiImplicitParam(value = "用户id（小程序需要此参数）", name = "uid", dataType = "String", paramType = "query"),
            @ApiImplicitParam(value = "当前页数", name="currentPage", required = true, dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(value = "每页条数", name = "pageSize", dataType = "Integer", paramType = "query", required = true)
    })
    @RequestMapping(value = "/getGroupList",method = RequestMethod.POST)
    public Result getGroupList(Integer currentPage, Integer pageSize, String groupName, String uid, String istoTeacher){
        Map<String,Object> map = new HashMap<>();
        UserEntity userEntity= (UserEntity)(SecurityUtils.getSubject().getSession().getAttribute("currentUser"));
        if (userEntity != null){
            map.put("schoolCode", userEntity.getSchoolCode());
        }else {
            Integer schoolCode = userService.getSchoolCodeByUserId(uid);
            map.put("schoolCode", schoolCode);
        }
        if (groupName != null && !"".equals(groupName)){
            map.put("groupName", groupName);
        }
        if (StringUtils.isNoneBlank(istoTeacher)){
            map.put("istoTeacher", istoTeacher);
        }
        if (currentPage != null && !"".equals(currentPage)){
            map.put("page", (currentPage-1) * pageSize);
        }
        if (pageSize != null && !"".equals(pageSize)){
            map.put("total", pageSize);
        }
        List<GroupEntity> list = groupService.getGroupList(map);
        for (GroupEntity groupEntity : list) {
            List<String> groupUserIdList = Arrays.asList(groupEntity.getStaffList().split(","));
            List<String> groupUserNameList = Arrays.asList(groupEntity.getGroupUserName().split(","));
            groupEntity.setGroupUserIdList(groupUserIdList);
            groupEntity.setGroupUserNameList(groupUserNameList);
        }
        int total1 = groupService.getGroupListTotal(map);
        return  new Result().getResult(401,"查询成功",1,new PageBean<GroupEntity>().pageBeans(list,total1));
    }

    /**
     *   新增群主管理信息
     *
     * @return
     */
    @ApiOperation(value = "新增群主管理")
    @PostMapping(value = "/insertGroup")
    public Result insertGroup(@ModelAttribute GroupEntity groupEntity){
        // 判断组内人员不能为空
        if (!StringUtils.isNoneBlank(groupEntity.getGroupUserName()) || !StringUtils.isNoneBlank(groupEntity.getStaffList())){
            return new Result().getResult(402,"新增失败，您没有选择任何人员！",2,"");
        }
        UserEntity userEntity = (UserEntity)(SecurityUtils.getSubject().getSession().getAttribute("currentUser"));
        if (userEntity == null){
            userEntity = userService.getUserByUid(groupEntity.getTeacherId());
        }
        groupEntity.setTeacherId(userEntity.getId());
        int a = groupEntity.getGroupUserName().split(",").length;
        groupEntity.setGroupSize(a);
        groupEntity.setSchoolCode(userEntity.getSchoolCode());
        // 判断当前创建的群组名字是否已存在
        String groupName = groupEntity.getGroupName();
        Map<String, Object> params = new HashMap<>();
        params.put("schoolCode", userEntity.getSchoolCode());
        List<GroupEntity> groupList = groupService.getGroupList(params);
        for (GroupEntity group : groupList) {
            if (group.getGroupName().equals(groupName)){
                return new Result().getResult(402,"新增失败，当前创建的群组名称已存在！",2,"");
            }
        }

        // 去重
        String staffList = groupEntity.getStaffList().replace(" ", "");
        StringBuffer sb = new StringBuffer();
        List<String> staffIdList = Arrays.asList(staffList.split(","));
        Set<String> staffIdSet = new HashSet<>(staffIdList);
        staffIdList = new ArrayList<>(staffIdSet);
        for (String s : staffIdList) {
            sb.append(",").append(s);
        }
        if (staffList != null){
            groupEntity.setStaffList(sb.toString().substring(1));
        }
        int  code = groupService.insertGroup(groupEntity);
        if (code == 1){
            return new Result().getResult(401,"新增成功！",1,"");
        }else{
            return new Result().getResult(402,"新增失败！",2,"");
        }
    }


    /**
     *   删除群主管理信息
     * @return
     */
    @ApiOperation(value = "删除群主管理信息")
    @PostMapping(value = "/deleteGroupById")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "ID",name = "id",dataType = "int",paramType = "query",required = false)

    })
    public Result deleteGroupById(@RequestParam("id") int  id){
        int  code= groupService.deleteGroupById(id);
        if(code==1){
            return new Result().getResult(401,"删除成功！",1,"");
        }
        return new Result().getResult(402,"删除失败！",2,"");
    }

    /**
     * 分页获取所有教师
     * @param currentPage
     * @param pageSize
     * @param name
     * @return
     */
    @ApiOperation(value = "分页获取所有教师")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "schoolCode", value = "学校ID", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "name", value = "教师姓名", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name="currentPage", value = "当前页数", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数", dataType = "Integer", paramType = "query"),
    })
    @RequestMapping(value = "/getUserList",method = RequestMethod.POST)
    public Result getUserList(Integer currentPage, Integer pageSize, String name, Integer schoolCode){
        PageHelper.startPage(currentPage, pageSize);
        List<UserEntity> list = userService.listSchoolTeacher(schoolCode, null, null, null, name);
        int total1 = userService.countSchoolTeacher(schoolCode, null, null, null, name);
        return  new Result().getResult(401,"查询成功",1,new PageBean<UserEntity>().pageBeans(list, total1));
    }

    /**
     * 分页获取所有家长
     * @param currentPage
     * @param pageSize
     * @param name
     * @return
     */
    @ApiOperation(value = "分页获取所有家长")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "学校ID",name = "schoolCode",dataType = "int",paramType = "query"),
            @ApiImplicitParam(value = "家长姓名",name = "name",dataType = "String",paramType = "query"),
            @ApiImplicitParam(value = "当前页数",name="currentPage",dataType = "Integer",paramType = "query"),
            @ApiImplicitParam(value = "每页条数",name = "pageSize",dataType = "Integer",paramType = "query"),
            @ApiImplicitParam(value = "年级id",name = "gradeId",dataType = "String",paramType = "query"),
            @ApiImplicitParam(value = "班级id",name = "classId",dataType = "String",paramType = "query"),
    })
    @RequestMapping(value = "/getParentList",method = RequestMethod.POST)
    public Result getParentList(Integer currentPage, Integer pageSize, String name, String schoolCode, String gradeId, String classId){
        PageHelper.startPage(currentPage, pageSize);
        List<Map<String,Object>> list = parentService.listSchoolParent(schoolCode, gradeId, classId, name);
        int total1 = parentService.countSchoolParent(schoolCode, gradeId, classId, name);
        return new Result().getResult(401,"查询成功",1,new PageBean<Map<String,Object>>().pageBeans(list, total1));
    }

    @ApiOperation(value = "获取某一个群组的所有人员id")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "群组id",name = "groupId",dataType = "Integer",paramType = "query"),
    })
    @PutMapping(value = "/list-group-user")
    public Msg listGroupUser(Integer groupId){
        List<String> userIdList = groupService.listGroupUser(groupId);
        return Msg.success().add("userIdList", userIdList);
    }

    @ApiOperation(value = "修改群组信息")
    @PutMapping(value = "/update-group")
    public Msg updateGroup(@RequestBody GroupSimpleEntity groupSimpleEntity){
        UserEntity userEntity = (UserEntity)(SecurityUtils.getSubject().getSession().getAttribute("currentUser"));
        if (userEntity != null){
            groupSimpleEntity.setCreateUserId(userEntity.getId()).setSchoolCode(userEntity.getSchoolCode());
        }
        boolean result = groupService.updateGroup(groupSimpleEntity);
        if (result)
            return Msg.success();
        return Msg.fail(ErrorEnum.E_101, ErrorEnum.E_101.getErrorMsg());
    }







}
